<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--通用查询-->
      <queryHeader :permission="permission" />
      <!--通用编辑-->
      <crudOperation :permission="permission">
        <template slot="left">
          <el-button class="filter-item" type="warning" icon="el-icon-delete" size="mini" :disabled="crud.selections.length === 0" @click="qrcode(crud.selections)">
            二维码
          </el-button>
        </template>
      </crudOperation>
    </div>

    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
      <!--多选框-->
      <el-table-column type="selection" width="55" />
      <!--展示字段-->
      <el-table-column v-if="columns.visible('deviceSerial')" prop="deviceSerial" label="设备编号" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('bleMac')" prop="bleMac" label="蓝牙mac地址" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('hospitalName')" prop="hospitalName" label="医院名称" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('buildingName')" prop="buildingName" label="楼栋名称" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('floorName')" prop="floorName" label="楼层名称" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('departName')" prop="departName" label="科室名称" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('deviceStatus')" prop="deviceStatus" label="设备状态" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ dict.label.status_device[scope.row.deviceStatus] }}
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('devicePublishStatus')" prop="devicePublishStatus" label="设备投放状态" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ dict.label.status_device_publish[scope.row.devicePublishStatus] }}
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('batteryBoard')" prop="batteryBoard" label="主板电量" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('batteryBoardAlarm')" prop="batteryBoardAlarm" label="主板电量报警" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('batteryLock')" prop="batteryLock" label="锁电量" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('batteryLockAlarm')" prop="batteryLockAlarm" label="锁电量报警" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('hardVer')" prop="hardVer" label="硬件版本" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('softVer')" prop="softVer" label="软件版本" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('deviceRemark')" prop="deviceRemark" label="设备备注" :show-overflow-tooltip="true" />
      <el-table-column v-if="columns.visible('deviceImgs')" prop="deviceImgs" label="设备图片" :show-overflow-tooltip="true" />

      <!--操作-->
      <el-table-column label="操作" width="280px" align="center" fixed="right">
        <template slot-scope="scope">
          <!--通用编辑删除-->
          <udOperation :data="scope.row" :permission="permission">
            <template slot="left">
              <el-button v-if="scope.row.deviceStatus === 1" size="mini" type="text" @click="deviceGz(scope.row)">
                设备故障
              </el-button>
              <el-button v-if="scope.row.deviceStatus === 3" size="mini" type="text" @click="deviceGzXf(scope.row)">
                故障修复
              </el-button>
              <el-button v-if="scope.row.devicePublishStatus === 2" size="mini" type="text" @click="doTf(scope.row)">
                设备上架
              </el-button>
              <el-button v-if="scope.row.devicePublishStatus === 1" size="mini" type="text" @click="deviceXj(scope.row)">
                设备下架
              </el-button>
              <el-button v-if="scope.row.deviceStatus === 2" size="mini" type="text" @click="sjkzl(scope.row)">
                实际可租赁
              </el-button>
            </template>
          </udOperation>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <pagination />

    <!--表单渲染-->
    <editForm :dict="dict" />

    <el-dialog append-to-body :visible.sync="tfDialog" title="设备投放" width="400px">
      <el-form ref="tfForm" :model="deviceTfData" :rules="tfRules" size="small" label-width="120px">
        <el-form-item label="部署医院" prop="hospitalId">
          <el-select v-model="deviceTfData.hospitalId" placeholder="请选择" @change="hospitalChange">
            <el-option v-for="item in hospitals" :key="item.hospitalId" :label="item.hospitalName" :value="item.hospitalId" />
          </el-select>
        </el-form-item>
        <el-form-item label="部署科室" prop="departId">
          <el-select v-model="deviceTfData.departId" placeholder="请选择">
            <el-option v-for="item in departs" :key="item.departId" :label="item.departName" :value="item.departId" />
          </el-select>
        </el-form-item>
        <el-form-item label="部署楼栋" prop="buildingId">
          <el-select v-model="deviceTfData.buildingId" placeholder="请选择" @change="ldChange">
            <el-option v-for="item in buildings" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部署楼层" prop="floorId">
          <el-select v-model="deviceTfData.floorId" placeholder="请选择">
            <el-option v-for="item in floors" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="tfDialog=false">取消</el-button>
        <el-button type="primary" @click="deviceSj">确认</el-button>
      </div>

    </el-dialog>

    <div id="qrcode" style="display:none" />

  </div>

</template>

<script>
import crudDevice, { gz, gzxf, xj, sj, kzlxg, rcodeFile } from '@/api/business/bed/device'
import { getHospitals } from '@/api/business/bed/hospital'
import { getDeparts } from '@/api/business/bed/depart'
import { getLDList } from '@/api/business/bed/building'
import queryHeader from './module/queryHeader'
import editForm from './module/editForm'
import CRUD, { presenter } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import udOperation from '@crud/UD.operation'
import { MessageBox } from 'element-ui'

// crud交由presenter持有
const crud = CRUD({ title: 't_device', url: 'device/list/page/token', crudMethod: { ...crudDevice }, pkIdName: 'deviceId' })

export default {
  name: 'Device',
  components: { queryHeader, editForm, crudOperation, pagination, udOperation },
  dicts: ['status_device', 'status_device_publish'],
  mixins: [presenter(crud)],
  data() {
    return {
      tfDialog: false,
      deviceTfData: {},
      tfRules: {
        hospitalId: [{ required: true, message: '医院不能为空', trigger: 'blur' }],
        departId: [{ required: true, message: '科室不能为空', trigger: 'blur' }],
        buildingId: [{ required: true, message: '楼栋不能为空', trigger: 'blur' }],
        floorId: [{ required: true, message: '楼层不能为空', trigger: 'blur' }]
      },
      hospitals: [],
      buildings: [],
      floors: [],
      departs: [],
      // 对应几个按钮操作
      permission: {
        add: [],
        edit: [],
        del: []
      }
    }
  },
  created() {
    getHospitals().then((data) => {
      this.hospitals = data
    })
  },
  methods: {
    sjkzl(row) {
      MessageBox.confirm('您是否想进行设备状态修改确认操作', '操作提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          kzlxg(row.deviceId).then(() => {
            this.crud.toQuery()
          })
        })
    },
    hospitalChange(val) {
      getDeparts(val).then((data) => {
        this.departs = data
      })
      getLDList(val, 0).then((data) => {
        this.buildings = data
      })
    },
    ldChange(val) {
      getLDList(this.deviceTfData.hospitalId, val).then((data) => {
        this.floors = data
      })
    },
    qrcode(selections) {
      const _this = this
      for (let i = 0; i < selections.length; i++) {
        (function(device) {
          _this.downloadNow(device.deviceSerial)
        })(selections[i])
      }
    },
    deviceGz(row) {
      MessageBox.confirm('您是否想进行故障确认操作', '操作提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          gz(row.deviceId).then(() => {
            this.crud.toQuery()
          })
        })
    },
    deviceGzXf(row) {
      MessageBox.confirm('您是否想进行故障确认操作', '操作提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          gzxf(row.deviceId).then(() => {
            this.crud.toQuery()
          })
        })
    },
    doTf(row) {
      this.deviceTfData.deviceId = row.deviceId
      this.tfDialog = true
    },
    deviceSj() {
      const _this = this
      this.$refs['tfForm'].validate(valid => {
        if (!valid) {
          return
        }
        sj(this.deviceTfData).then(() => {
          _this.tfDialog = false
          _this.crud.toQuery()
        })
      })
    },
    deviceXj(row) {
      MessageBox.confirm('您是否想下架该设备', '操作提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          xj(row.deviceId).then(() => {
            this.crud.toQuery()
          })
        })
    },
    downloadNow(serial) {
      // 请求路径
      rcodeFile(serial).then(res => {
        const blob = new Blob([res])
        const fileName = serial + '.png'
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        this.$message.success('生成文件成功')
      })
        .catch(err => {
          console.log(err)
          this.$message.error('服务器出现问题,请稍后再试')
        })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
